package com.sc.web.gwt.client.view.loginwidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;

public class LoginWidgetViewImpl extends Composite implements LoginWidgetView {
    private static Binder binder = GWT.create(Binder.class);

    public interface Binder extends UiBinder<HTMLPanel, LoginWidgetViewImpl> {
    }

    private Presenter presenter;

    @UiField
    TextBox userName;

    @UiField
    PasswordTextBox password;

    @UiField
    Button login;

    @UiField
    Button cancel;

    public LoginWidgetViewImpl() {
        initWidget(binder.createAndBindUi(this));
        clearFields();
    }

    public void setPresenter(Presenter presenter) {
        this.presenter = presenter;
    }

    @UiHandler("password")
    public void passwordEnterHandler(KeyPressEvent event){
        if (event.getNativeEvent().getKeyCode() == 13){
            login.click();
        }
    }

    @UiHandler("userName")
    public void userNameEnterHandler(KeyPressEvent event){
        if (event.getNativeEvent().getKeyCode() == 13){
            login.click();
        }
    }

    @UiHandler("login")
    public void loginClickHandler(ClickEvent event) {
        presenter.login(userName.getText(), password.getText());
    }

    @UiHandler("cancel")
    public void cancelClickHandler(ClickEvent event) {
        presenter.clearFields();
    }

    public void clearFields() {
        userName.setText("");
        password.setText("");
    }

    public void popErrorPanel(String msg)   {
        Window.alert(msg);
    }
}
